package de.nak.fireDepartment.visitorAction;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.web.struts.LookupDispatchActionSupport;

import de.nak.fireDepartment.actionForms.CarForm;
import de.nak.fireDepartment.model.Car;
import de.nak.fireDepartment.service.CarService;

/**
 * Actionclass that shows a selected Car
 * 
 * @author Nils Bredow
 */
public class CarAction extends LookupDispatchActionSupport {

	/**
	 * This method shows the selected car into the carForm
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return actionforward
	 * @throws Exception
	 */	
	public ActionForward showCar(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		// ActionForm => CarForm
		CarForm carForm = (CarForm) form;
		CarService carService = (CarService) getWebApplicationContext().getBean("carService");
		
		// if no line selected display error
		if(carForm.getSelectedKey()==null){
			carForm.setErrorCode("text.error.selectedKey");
			return mapping.findForward("cancel");
		}
		
		// get Car
		Car car = carService.showCar(carForm.getSelectedKey());		
		
		// if car has no image set default image
		if (car.getImageURL() == null || car.getImageURL().equals("")){
			car.setImageURL("/FireDepartmentManagement/images/layout/noImage.jpg");
		}
		
		// store car and data in form
		carForm.setCar(car);
		carForm.setEquipments(car.getEquipments());
		carForm.setDepartments(car.getDepartments());
		// Result result
		return mapping.findForward("show");
	}
	
	/** {@inheritDoc} */
	@Override
	protected Map<String, String> getKeyMethodMap() {
		Map<String, String> map = new HashMap<String, String>();
		map.put("button.show", "showCar");
		return map;
	}
}
